package com.liangsui.cmall.order.service.impl;

import com.liangsui.cmall.order.entity.OrderEntity;
import com.liangsui.cmall.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liangsui.common.utils.PageUtils;
import com.liangsui.common.utils.Query;

import com.liangsui.cmall.order.dao.OrderItemDao;
import com.liangsui.cmall.order.entity.OrderItemEntity;
import com.liangsui.cmall.order.service.OrderItemService;

@RabbitListener(queues = {"hello-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    //@RabbitListener(queues = {"hello-java-queue"})
    @RabbitHandler
    public void receiveMessage(Message message,
                               OrderReturnReasonEntity content,
                               Channel channel) {
        //消息体
        byte[] body = message.getBody();
        //消息头
        MessageProperties messageProperties = message.getMessageProperties();

        System.out.println("接收到消息：" + message + "内容：" + content);

        //channel按内容自增
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            if (deliveryTag % 2 == 0) {
                //b:是否开启批量接受模式
                channel.basicAck(deliveryTag, false);
                System.out.println("签收了货物");
            } else  {
                //b为是否开启批量接受模式，b1为是否放回消息队列
                channel.basicNack(deliveryTag, false ,false);
                //只能直接丢弃
                //channel.basicReject(deliveryTag, false);
                System.out.println("拒收了货物");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RabbitHandler
    public void receiveMessage2(OrderEntity content) {
        System.out.println("接收到消息内容：" + content);
    }

}